package com.proxy.daijia.customer.service.impl;

import com.proxy.daijia.common.constant.RedisConstant;
import com.proxy.daijia.common.execption.ProxyException;
import com.proxy.daijia.common.result.Result;
import com.proxy.daijia.common.result.ResultCodeEnum;
import com.proxy.daijia.common.util.AuthContextHolder;
import com.proxy.daijia.customer.client.CustomerInfoFeignClient;
import com.proxy.daijia.customer.service.CustomerService;
import com.proxy.daijia.model.vo.customer.CustomerInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class CustomerServiceImpl implements CustomerService {

    @Autowired
    private CustomerInfoFeignClient client;

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public String login(String code) {

        //远程调用
        Result<Long> longResult = client.login(code);

        if (longResult.getCode() != 200) {
            throw new ProxyException(longResult.getCode(), longResult.getMessage());
        }
        Long customerId = longResult.getData();
        if (customerId == null) {
            throw new ProxyException(ResultCodeEnum.DATA_ERROR);
        }

        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(RedisConstant.USER_LOGIN_KEY_PREFIX+token, customerId.toString(), RedisConstant.USER_LOGIN_KEY_TIMEOUT, TimeUnit.SECONDS);
        return token;
    }

    //获取登录信息
    @Override
    public CustomerInfoVo getCustomerLoginInfo() {

        Long customerId = AuthContextHolder.getUserId();

        Result<CustomerInfoVo> customerInfoVoResult = client.getCustomerInfoVo(customerId);
        if (customerInfoVoResult.getCode() != 200) {
            throw new ProxyException(customerInfoVoResult.getCode(), customerInfoVoResult.getMessage());
        }

        CustomerInfoVo customerInfoVo = customerInfoVoResult.getData();
        if (customerInfoVo == null) {
            throw new ProxyException(ResultCodeEnum.DATA_ERROR);
        }

        return customerInfoVo;
    }
}
